package com.qitianyong.sgkusbcamera;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.util.Log;

import com.gkusbsdk.GKUSBCommand;
import com.gkusbsdk.GKUSBSDK;
import com.gkusbsdk.GKUSBTime;
import com.qitianyong.selfclass.CONSTANT;
import com.qitianyong.selfclass.FindDeviceThread;
import com.qitianyong.selfclass.GKDevice;
import com.qitianyong.selfclass.PublicMethod;
import com.qitianyong.selfclass.UsbDeviceFilter;

import java.util.ArrayList;


public class TimeChangedReceiver extends BroadcastReceiver {

    private static  long lasTimeL;
    private Context context;

    @Override
    public void onReceive(Context context, Intent intent) {
        long currentTime = System.currentTimeMillis() / 1000;
        if(Math.abs(lasTimeL - currentTime)<30){
            return;
        }
        lasTimeL = currentTime;
        try {
            this.context = context;
            ArrayList<UsbDevice> matchingHostDevices = UsbDeviceFilter.getMatchingHostDevices(this.context, R.xml.device_filter);
            if(matchingHostDevices.size()>0){
                if(GKDevice.__hDevice!=0&&GKDevice.__device!=null){
                    GKUSBTime usbTime = PublicMethod.CurrentTime2USBTime();
                    Log.i("GKDevice", "time:" + usbTime.__year + "-" + usbTime.__month + "-" + usbTime.__day +
                            " " + usbTime.__hour + ":" + usbTime.__minute + ":" + usbTime.__second);
                    GKDevice.getInstance().sendCommand(CONSTANT.COMMAND.CMD_SYNC_TIME, usbTime);
                }else if(GKDevice.__hDevice!=0&&GKDevice.__device==null){
                    GKUSBTime usbTime = PublicMethod.CurrentTime2USBTime();
                    Log.i("GKDevice", "time:" + usbTime.__year + "-" + usbTime.__month + "-" + usbTime.__day +
                            " " + usbTime.__hour + ":" + usbTime.__minute + ":" + usbTime.__second);
                     GKUSBSDK.GKUSB_SetParam(GKDevice.__hDevice, GKUSBCommand.CMD_SYNC_TIME,usbTime);
                }else {
                    FindDeviceThread.getInstance().setIntent(FindDeviceThread.SYNC_TIME);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
